const app = getApp();
Page({
  data: {
    orders: [], 
  },
  onLoad: function (options) {
    const windowInfo = wx.getWindowInfo();
    this.setData({
      statusBarHeight: windowInfo.statusBarHeight
    });
    this.loadOrders();
  },

  onBack: function () {
    wx.navigateBack({
      delta: 1
    });
  },
  // 加载订单数据
  async loadOrders() {
    const orders = await this.getOrdersList();
    const ordersWithDetails = await this.getOrdersDetails(orders);
    
    this.setData({
      orders: ordersWithDetails.map(order => ({
        ...order,
        orderTime: this.formatDate(order.orderTime)
      })),
    });
  },

  // 获取订单列表
  getOrdersList() {
    return new Promise((resolve, reject) => {
      const userId=app.globalData.userInfo.id;
      const token=app.globalData.token;
      wx.request({
        url: `http://localhost:8080/manage/orders/list`,
        method: 'GET',
        data : { 
          userId: userId,
          status: 0
        },
        header: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        success: res => {
          if (res.statusCode === 200 && res.data.code === 200) {
            resolve(res.data.rows); // 根据实际返回结构调整
          } else {
            reject(new Error('获取订单列表失败'));
          }
        },
        fail: () => reject(new Error('网络请求失败'))
      });
    });
  },

  // 批量获取订单详情
  async getOrdersDetails(orders) {
    const promises = orders.map(order => 
      this.getOrderDetail(order.id).then(details => {
        // 计算实付金额
        console.log('订单详情数据:', details);
        const totalAmount = details.reduce((sum, item) => {
          return sum + (Number(item.amount) * parseInt(item.number));
          }, 0).toFixed(2);
        return {
          ...order,
          amount: totalAmount, // 用计算值覆盖原始金额
          items: details.map(d => ({
            name: d.name,
            price: d.amount.toFixed(2),
            quantity: d.number
          }))
        }
      })
    );
    return Promise.all(promises);
  },

  // 获取单个订单详情
  getOrderDetail(orderId) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `http://localhost:8080/manage/detail/list`,
        method: 'GET',
        data: { orderId },
        success: res => {
          if (res.statusCode === 200 && res.data.code === 200) {
            resolve(res.data.rows); // 根据实际返回结构调整
          } else {
            reject(new Error('获取详情失败'));
          }
        },
        fail: () => reject(new Error('网络请求失败'))
      });
    });
  },

  // 日期格式化方法
  formatDate(timestamp) {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
  },

  deleteOrder(e) {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个订单吗？',
      success: (res) => {
        if (res.confirm) {
          const app = getApp();
          const token = app.globalData.userInfo.token;
          wx.request({
            url: `http://localhost:8080/manage/orders`,
            method: 'PUT',
            header: {
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json'
            },
            data : { 
              id : e.currentTarget.dataset.id,
              status : 1,
              imageUrl : '',
              assess : ''
            },
            success: res=>{
              this.loadOrders();
            },
            fail: (err) => {
              wx.showToast({
                title: '网络错误，请重试',
                icon: 'none'
              });
            }
          });
        }
      }
    })
  }
})